<?php
/**
 * Created by PhpStorm.
 * User: jyolo
 * Date: 2017/2/5
 * Time: 17:20
 */

namespace app\base\validate;
use think\Validate;
use think\Db;

class Login extends Validate
{

    protected $rule = [
        'login_name' => 'require|max:20',
        'login_pwd' => 'require|min:6',
        'captcha'=>'require|diffCaptcha:thinkphp'
    ];

    protected $message = [
        'login_name.require' => '请输入登录用户名',
        'login_name.max' => '登录用户名最大长度为20',
        'login_pwd.require' => '请输入密码',
        'login_pwd.min' => '密码不能小于6位数',
        'captcha.require' => '请输入验证码',
        'captcha.diffCaptcha:thinkphp' => '验证码不正确',
    ];

    public function check_isright_manager($data){
        $manager = $this->check_isset($data['login_name']);
        if(!$manager) return false;
        $isright_pwd = $this->check_pwd($data['login_pwd'] ,$manager);
        if(!$isright_pwd) return false;
        $isright_status = $this->check_status($manager['status'] );
        if(!$isright_status) return false;

        return $manager;
    }

    //检查是否用户是否存在
    protected function check_isset($name){

        $manager = Db::name('manager')->where('login_name' , $name)->find();
        if(!$manager){
            $this->error = '管理员不存在';
            return false;
        }

        $roles = Db::name('role')->field('role_name')->where('id','in' , $manager['role_id'])->select();
        $role_name = '';
        foreach($roles as $k => $v){
            $role_name .= $v['role_name'].',';
        }
        $role_name = trim($role_name ,',');
        $manager['role_name'] = $role_name;

        return $manager;
    }
    //检查密码是否正确
    protected  function check_pwd($pwd ,&$manager){

        $enter_pwd = md5(md5($pwd).$manager['encrypt']);

        if($enter_pwd != $manager['login_pwd']){
            $this->error = '密码不正确';
            return false;
        }
        //卸载敏感数据
        unset($manager['login_pwd']);
        unset($manager['encrypt']);
        return true;
    }
    //检查管理员状态
    protected function check_status($status){
        if($status == 1){
            $this->error = '您的账户已被冻结，请及时联系管理员';
            return false;
        }
        return true;
    }

    protected function diffCaptcha($vaule){

        if(captcha_check($vaule ,'login') == false)return '验证码不正确';

        return true;

    }
}